// pages/add_address/address.js
const app = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')
var qqmapsdk

Page({
  /**
   * 页面的初始数据
   */
  data: {
    text: '添加',
    content: '',
    duration: 2000,
    $zanui: {
      toptips: {
        show: false,
      },
    },
    region: '请选择',
    latitude: '', //纬度
    longitude: '', //经度
  },

  /**
   * 发送数据
   */
  sendData: function (e) {
    console.log('北纬', this.data.latitude)
    console.log('东经', this.data.longitude)
    let arr = e.detail
    let phoneTest = /^1(3|4|5|7|8)\d{9}$/;
    if (arr.name == '') {
      this._topCue('请输入姓名')
      return
    }
    if (arr.phone == '') {
      this._topCue('请输入电话号码')
      return
    }

    if(!phoneTest.test(arr.phone)) {
      this._topCue('您输入的手机号不合法，请重新输入!')
      return
    }
    if (arr.region == '' || arr.region == '请选择') {
      this._topCue('请选择所在地区')
      return
    }
    if (arr.content.length <= 5) {
      this._topCue('详情地址不少于5个字')
      return
    }

    // 执行发送请求
    this.doSend(arr)
  },
  // =============================执行收货地址添加请求👇==========================================//
  doSend(arr) {

    let sendData = {
      address: arr.region,
      detailed: arr.content,
      isdefault: arr.select,
      addressee: arr.name,
      phone: arr.phone,
      userId: app.globalDataO.openid.objectSid,
      sex: 1,
    }
    app.post(app.url.address.addAddress, sendData).then(re => {
      if (re.statusCode == 200) {
        this._topCue(re.data.msg)
        wx.navigateBack({
          delta: 1
        })
      } else {
        this._topCue(re.data.msg)
      }
    })
  },
  // =============================执行收货地址添加请求👆==========================================//

  /**
   * 顶部提示
   */
  _topCue: function (text) {
    this.setData({
      content: text,
      $zanui: {
        toptips: {
          show: true,
        },
      },
    })

    setTimeout(() => {
      this.setData({
        $zanui: {
          toptips: {
            show: false,
          },
        },
      })
    }, this.data.duration)
  },

  /**
   * 从新定位
   */
  _newSeat: function () {
    this.getUserLocation()
  },

  getUserLocation: function () {
    let vm = this
    wx.getSetting({
      success: res => {
        // console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (
          res.authSetting['scope.userLocation'] != undefined &&
          res.authSetting['scope.userLocation'] != true
        ) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000,
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (
                      dataAu.authSetting[
                      'scope.userLocation'
                      ] == true
                    ) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000,
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000,
                      })
                    }
                  },
                })
              }
            },
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation()
        } else {
          //调用wx.getLocation的API
          vm.getLocation()
        }
      },
    })
  },

  // 微信获得经纬度
  getLocation: function () {
    let vm = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log('获取的地理位置信息：', res)
        // console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy

        // 存储经纬度
        vm.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      },
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this
    console.log(qqmapsdk, latitude, longitude)
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude,
      },
      get_poi: 1,
      poi_options: 'policy=2;radius=3000;page_size=20;page_index=1',
      success: function (res) {
        console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        vm.setData({
          region: province + ' - ' + city + ' - ' + district,
        })
      },
      fail: function (res) {
        console.log(52)
        console.log(res)
      },
      complete: function (res) {
        console.log(53)
        console.log(res);
      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: '33XBZ-4KSWU-HNAV4-BW2XL-YG6RJ-YZFPN', //这里自己的key秘钥进行填充
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserLocation()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
})